package com.hyfrogx.modules.operation.service.umeng.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.log.LogEnum;
import com.hyfrogx.common.log.LogUtils;
import com.hyfrogx.common.utils.*;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.StringUtils;
import com.hyfrogx.modules.manage.entity.task.TaskEntity;
import com.hyfrogx.modules.manage.service.task.TaskService;
import com.hyfrogx.modules.operation.dao.HyAppPushConfigDao;
import com.hyfrogx.modules.operation.dao.HyAppPushDao;
import com.hyfrogx.modules.operation.entity.HyAppPushConfigEntity;
import com.hyfrogx.modules.operation.entity.HyAppPushEntity;
import com.hyfrogx.modules.operation.service.umeng.AndroidNotification;
import com.hyfrogx.modules.operation.service.umeng.OldPushClient;
import com.hyfrogx.modules.operation.service.umeng.PushClient;
import com.hyfrogx.modules.operation.service.umeng.UmengService;
import com.hyfrogx.modules.operation.service.umeng.android.AndroidBroadcast;
import com.hyfrogx.modules.operation.service.umeng.android.AndroidUnicast;
import com.hyfrogx.modules.operation.service.umeng.ios.IOSBroadcast;
import com.hyfrogx.modules.operation.service.umeng.ios.IOSUnicast;
import com.hyfrogx.modules.push.notification.UmAndriodNotification;
import com.hyfrogx.modules.push.config.UmConfig;
import com.hyfrogx.modules.push.util.UmPushUtil;
import com.hyfrogx.modules.zoom.entity.HyZoomMeeting;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liubin
 */
@Service("UmengService")
@Slf4j
public class UmengServiceImpl extends ServiceImpl<HyAppPushDao, HyAppPushEntity> implements UmengService {

    private static String appkey = "5c9b05a80cafb2a366000daf";

    private static String appMasterSecret = "xbigwfgaeuc48ha1yjliezpozq4cnpde";


    private static String appkey_ios = "5c9b05720cafb2399e0005cc";

    private static String appMasterSecret_ios = "zhk0iguywrlz4v8kjeghgxpuwe0w4olo";

    Logger UMENG_LOG = LogUtils.Logger(LogEnum.UMENG_LOGS);
    Logger LOGIN_LOG = LogUtils.Logger(LogEnum.LOGIN_LOGS);


    // 用户device_token
    Map<String, Object> device_token_cache = new ConcurrentHashMap<>();
    // 创建对象
    private Map<Object, Object> cacheManager;

    @Autowired
    HyAppPushDao appPushDao;

    @Autowired
    HyAppPushConfigDao appPushConfigDao;

    @Autowired
    TaskService taskService;

    @Autowired
    UserService userService;

    @Autowired
    RedisUtils redisUtils;

    // 启动就执行
    @PostConstruct
    private Map<Object, Object> getCacheManage() {
        //获取已经存在的cache实例
        cacheManager = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN);
        //如果不存在就创建新的缓存实例
        if (cacheManager == null) {
            redisUtils.setMap(FrogConstant.RedisKey.DEVICE_TOKEN, new ConcurrentHashMap<>());
        }
        return cacheManager;
    }

    @Override
    public void init() {
        //初始化
        //通过key获取map对象集合
        Map<Object, Object> remains = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN);
        if (remains.size() == 0) {
            device_token_cache.put("uid","device_token_cache");
            redisUtils.setMap(FrogConstant.RedisKey.DEVICE_TOKEN, device_token_cache);
        } else {
            for (Map.Entry<Object, Object> entry : remains.entrySet()) {
                device_token_cache.put(entry.getKey().toString(), entry.getValue());
            }
        }

    }

    //用户登录时添加deviceToken
    @Override
    public void addDeviceToken(Integer uid, String device_token) {
        //获取已经存在的cache实例
        cacheManager = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN);
        LOGIN_LOG.info("cacheManager"+cacheManager);
        //如果不存在就创建新的缓存实例
        if (cacheManager == null) {
            LOGIN_LOG.info("创建新的缓存实例");
            device_token_cache.put(uid.toString(),device_token);
            redisUtils.setMap(FrogConstant.RedisKey.DEVICE_TOKEN, device_token_cache);
            LOGIN_LOG.info("uid:"+uid.toString()+",device_token:"+device_token);
        }
        if (!StringUtils.isBlank(device_token)) {
            LOGIN_LOG.info("device_token:"+device_token);
            redisUtils.put(FrogConstant.RedisKey.DEVICE_TOKEN,uid.toString(),device_token);
            LOGIN_LOG.info("更新token");
            LOGIN_LOG.info("uid:"+uid.toString()+",device_token:"+device_token);

        }
    }

    //定时任务存储
    @Override
    public void saveUserDeviceToken() throws Exception {
        synchronized (device_token_cache) {
            try {
                //通过获取二次map的key,put值
                redisUtils.get(FrogConstant.RedisKey.DEVICE_TOKEN);
            } catch (Exception ex) {
                UMENG_LOG.error("刷新出错");
                throw new Exception("刷新出错");
            }
        }
    }


    private HyAppPushEntity checkStartTime(HyAppPushEntity appPush) throws Exception {
        UMENG_LOG.info("校验发送时间");
        if (appPush.getType().intValue() == AppPushParam.AppPushType.current) {
            appPush.setStartTime(new Date());

        } else {
            if (appPush.getStartTime() == null) {
                UMENG_LOG.error("发送时间不能为空，apppush对象：" + appPush.toString());
                throw new Exception("定时发送时间不能为空");
            }
            // 校验最大3天时间
            Date date = DateUtils.addDateDays(new Date(), 3);
            if (date.getTime() <= appPush.getStartTime().getTime()
                    || System.currentTimeMillis() > appPush.getStartTime().getTime()) {
                UMENG_LOG.error("推送时间错误，AppPush对象：" + appPush.toString());
                throw new Exception("推送时间错误");
            }
        }
        return appPush;
    }

    /**
     * //根据config_value所属的模块查询对应的资源name是否存在
     *
     * @param custom
     * @param name
     * @return
     * @throws Exception
     */
    public Integer findIdByName(String custom, String name) throws Exception {
        UMENG_LOG.info("findIdByName,+CUSTOM:" + custom + ",NAME:" + name);
        Integer id = null;
        List<HyAppPushConfigEntity> config = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>().eq("config_value", custom));
        if (config.size() > 0) {
            UMENG_LOG.info("资源不存在");
            //根据config_value所属的模块查询对应的资源name是否存在
            throw new Exception("资源不存在");

        }
        UMENG_LOG.info("ID:" + id);
        return id;
    }

    /**
     * 群推安卓
     *
     * @param appPush
     * @return
     * @throws Exception
     */
    @Override
    public boolean sendAndroidBroadcast(HyAppPushEntity appPush) throws Exception {
        UMENG_LOG.info("群推安卓接口------------------------------------------------");
        // 校验时间
        appPush = checkStartTime(appPush);
        AndroidBroadcast broadcast = new AndroidBroadcast(appkey, appMasterSecret);
        // 如果是定时，设置时间
        if (appPush.getType().intValue() == AppPushParam.AppPushType.timing) {
            broadcast.setStartTime(appPush.getTaskStartDate());
        }else{
            appPush.setStartTime(new Date());
        }
        broadcast.setTitle(appPush.getTitle());
        broadcast.setText(appPush.getText());
        broadcast.setTicker(appPush.getTicker());
        // 设置为生产模式
        broadcast.setProductionMode();
        // 目前默认显示给用户信息
        // 如果后续需要改成APP自解析，根据appPush的displayType字段做修改
        AndroidNotification.DisplayType displayType = AndroidNotification.DisplayType.NOTIFICATION;
        broadcast.setDisplayType(displayType);
        if (appPush.getDisplayChannel().intValue() != Terminal.DisplayChannel.android) {
            UMENG_LOG.error("推送渠道参数错误,无法调用安卓群发接口,AppPush对象：" + appPush.toString());
            throw new Exception("推送渠道参数错误,无法调用安卓群发接口");
        }
        //设置推送渠道
        appPush.setDisplayChannel(Terminal.DisplayChannel.android);
        if (appPush.getAfterOpen().intValue() >= appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>()
                .eq("config_type", 1)) || appPush.getAfterOpen().intValue() < 0) {
            UMENG_LOG.error("点击通知行为不存在,AppPush对象：" + appPush.toString());
            throw new Exception("点击通知行为不存在");
        }

        String configValue = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                .eq("config_id", appPush.getAfterOpen()).eq("config_type", 1)).get(0)
                .getConfigValue();
        if (configValue.equals("go_app")) {
            broadcast.goAppAfterOpen();
        } else {
            // 验证自定义打开后操作
            //查询推送模块的数值区间
            int size = appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_type", 2));
            if (size <= appPush.getCustomAfterOpen().intValue() || appPush.getCustomAfterOpen().intValue() < 0) {
                UMENG_LOG.error("不存在的自定义custom,AppPush对象：" + appPush.toString());
                throw new Exception("不存在的自定义custom");
            }
            //获取CustomAfterOpenAction的configValue
            String custom = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction")
                    .eq("config_id", appPush.getCustomAfterOpen())).get(0).getConfigValue();

            JSONObject jsonObject = new JSONObject();
            //如果custom!=会议室
            if (custom.equals("go_zoom")) {
                jsonObject.put("data",appPush.getSid().toString());
                UMENG_LOG.info("非会议室，broadcast:" + broadcast.toString());
            } else {
                jsonObject.put("data", appPush.getNameUrl());
            }

            // 自定义打开url的操作
            jsonObject.put("custom",custom);
            broadcast.setCustomField(jsonObject);
            broadcast.setAfterOpenAction(AndroidNotification.AfterOpenAction.go_custom);
        }
        boolean status = new PushClient().send(broadcast, appPush);
        if (status) {
            if (appPush.getType().intValue() == AppPushParam.AppPushType.current) {
                appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_success);
            } else {
                appPush.setDisplayStatus(AppPushParam.AppPushStatus.timing);
            }
            appPushDao.insert(appPush);
            return true;
        } else {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_fail);
            appPushDao.insert(appPush);
            return false;
        }
    }

    /**
     * 苹果群发
     *
     * @param appPush
     * @return
     * @throws Exception
     */
    @Override
    public boolean sendIOSBroadcast(HyAppPushEntity appPush) throws Exception {
        UMENG_LOG.info("苹果群发--------------------AppPush:" + appPush.toString());
        appPush = checkStartTime(appPush);
        IOSBroadcast broadcast = new IOSBroadcast(appkey_ios, appMasterSecret_ios);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", appPush.getTitle());
//		jsonObject.put("subtitle", appPush.getTicker());
        jsonObject.put("body", appPush.getText());
        broadcast.setAlert(jsonObject);
        broadcast.setBadge(0);
        broadcast.setSound("default");
        if (IPUtils.checkIp() == true) {
            UMENG_LOG.info("设置生产模式---------------------IOSBroadcast：" + broadcast.toString());
            //broadcast.setProductionMode();
            broadcast.setTestMode();
        } else {
            UMENG_LOG.info("设置测试模式---------------------IOSBroadcast：" + broadcast.toString());
            broadcast.setTestMode();
        }


        // 设置时间
        if (appPush.getType().intValue() == AppPushParam.AppPushType.timing) {
            broadcast.setStartTime(appPush.getTaskStartDate());
            UMENG_LOG.info("设置推送时间：" + broadcast.toString());
        }else{
            appPush.setStartTime(new Date());
        }
        // 验证推送渠道
        if (appPush.getDisplayChannel().intValue() != Terminal.DisplayChannel.ios) {
            UMENG_LOG.error("推送渠道参数错误,无法调用ios群发接口,AppPush对象：" + appPush.toString());
            throw new Exception("推送渠道参数错误,无法调用ios群发接口");
        }
        // 设置推送渠道
        appPush.setDisplayChannel(Terminal.DisplayChannel.ios);
        //获取AfterOpenAction的个数
        int afterOpenActionNum = appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>()
                .eq("config_name", "AfterOpenAction"));
        UMENG_LOG.info("获取AfterOpenAction的个数:" + afterOpenActionNum);
        if (afterOpenActionNum <= appPush.getAfterOpen() || appPush.getAfterOpen() < 0) {
            UMENG_LOG.error("点击通知行为不存在,无法调用ios群发接口,AppPush对象：" + appPush.toString());
            throw new Exception("点击通知行为不存在");
        }
        // 打开APP自定义操作
        //cuostomUrl = (configName = CustomAfterOpenAction,config_id =appPush.getCustomAfterOpen()）的configValue
        String customUrl = appPushConfigDao
                .selectList(new QueryWrapper<HyAppPushConfigEntity>()
                        .eq("config_name", "AfterOpenAction")
                        .eq("config_id", appPush.getAfterOpen()))
                .get(0)
                .getConfigValue();
        UMENG_LOG.info("获取cuostomUrl:" + customUrl);


        if (customUrl.equals("go_app")) {
            //customizedField = configName
            broadcast.setCustomizedField("custom", "go_app");
        } else if (customUrl.equals("go_custom")) {
            //custom = (configName = AfterOpenAction,config_id =appPush.getAfterOpen()）的configValue
            String custom = appPushConfigDao
                    .selectList(new QueryWrapper<HyAppPushConfigEntity>()
                            .eq("config_name", "CustomAfterOpenAction")
                            .eq("config_id", appPush.getCustomAfterOpen()))
                    .get(0)
                    .getConfigValue();
            UMENG_LOG.info("获取cuostom:" + custom);
            //size =CustomAfterOpenAction的个数
            int size = appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction"));
            if (size <= appPush.getCustomAfterOpen() || appPush.getCustomAfterOpen() < 0) {
                UMENG_LOG.error("不存在的自定义custom,无法调用ios群发接口,AppPush对象：" + appPush.toString());
                throw new Exception("不存在的自定义custom");
            }

            //如果custom!=会议室
            if (customUrl.equals("go_zoom")) {
                broadcast.setCustomizedField("data", appPush.getSid().toString());
                UMENG_LOG.info("非会议室，broadcast:" + broadcast.toString());
            } else {
                broadcast.setCustomizedField("data", appPush.getNameUrl());
            }

            //
            broadcast.setCustomizedField("custom",custom );
            UMENG_LOG.info("brodacast设置custom，broadcast:" + broadcast.toString());
        } else {
            broadcast.setCustomizedField("data", appPush.getNameUrl());
            broadcast.setCustomizedField("custom", customUrl);
            UMENG_LOG.info("brodacast设置data和custom，broadcast:" + broadcast.toString());
        }
        boolean status = new PushClient().send(broadcast, appPush);
        if (status) {
            if (appPush.getType().intValue() == AppPushParam.AppPushType.current) {
                UMENG_LOG.info("已提交,定时推送");
                appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_success);
            } else {
                appPush.setDisplayStatus(AppPushParam.AppPushStatus.timing);
                UMENG_LOG.info("定时任务");
            }
            appPushDao.insert(appPush);
            UMENG_LOG.info("发送成功，插入记录，status:" + status);
            return status;
        } else {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_fail);
            appPushDao.insert(appPush);
            UMENG_LOG.info("发送失败，插入记录");
            return status;
        }

    }

    @Override
    public Page getAppPushRecordByPage(QueryExt query) throws Exception {
        Map map = new HashMap();
        map.putAll(query.getCondition());
        List<HyAppPushEntity> result = appPushDao.getAppPushRecordByPage(query, map);
        if(result.size()>0){
        for(HyAppPushEntity appPushEntity:result){
            if(appPushEntity.getCustomAfterOpen()!=null){
            String module = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_id",appPushEntity.getCustomAfterOpen())
                    .eq("config_type",2)).get(0).getConfigRemark();
            appPushEntity.setModule(module);
            }else{
                appPushEntity.setModule(null);
            }
            if(appPushEntity.getAppMessageType()!=null){
                String appMessage = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                        .eq("config_id",appPushEntity.getAppMessageType())
                        .eq("config_type",3)).get(0).getConfigRemark();
                appPushEntity.setAppMessage(appMessage);
            }else{
                appPushEntity.setAppMessage(null);
            }

        }
        }
        query.setRecords(result);
        return query;
    }

    @Override
    public boolean sendSingleBroadcast(HyAppPushEntity appPush) throws Exception {
        Long uid = userService.getOne(new QueryWrapper<User>().eq("phone", appPush.getPhone())).getUid();
        if (uid == null) {
            UMENG_LOG.error("用户不存在");
            return false;
        }
        appPush.setDisplayUid(uid);
        Object user_device_token = null;
        user_device_token = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(uid.toString()).toString();

        if (user_device_token == null) {
            UMENG_LOG.error("用户的设备token不存在,AppPush对象：" + appPush.toString());
            return false;
        }
        int size = user_device_token.toString().length();
        Boolean status = null;

        if (size == 44) {
            status = sendAndroidUnicast(appPush, user_device_token.toString());
        } else if (size == 64) {
            status = sendIOSUnicast(appPush, user_device_token.toString());
        } else {
            UMENG_LOG.error("用户设备信息不存在,AppPush对象：" + appPush.toString());
            throw new Exception("用户设备信息不存在");
        }
        return status;
    }

    /**
     * 安卓单推
     *
     * @param appPush
     * @param user_device_token
     * @return
     * @throws Exception
     */
    public boolean sendAndroidUnicast(HyAppPushEntity appPush, String user_device_token) throws Exception {
//		appPush = checkStartTime(appPush);
        appPush.setDisplayChannel(Terminal.DisplayChannel.android);
        AndroidUnicast unicast = new AndroidUnicast(appkey, appMasterSecret);
        appPush.setStartTime(new Date());
        // 设置时间
        if (appPush.getType().intValue() == AppPushParam.AppPushType.timing) {
//			unicast.setStartTime(DateUtils.format(appPush.getStartTime()));
            UMENG_LOG.error("单推不能选择定时发送,AppPush对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
            throw new Exception("单推不能选择定时发送");
        }
        appPush.setType(AppPushParam.AppPushType.current);
        unicast.setDeviceToken(user_device_token);
        unicast.setTicker(appPush.getTicker());
        unicast.setTitle(appPush.getTitle());
        unicast.setText(appPush.getText());
        // 设置为生产模式
        unicast.setProductionMode();
        // 目前默认显示给用户信息
        // 如果后续需要改成APP自解析，根据appPush的displayType字段做修改
        AndroidNotification.DisplayType displayType = AndroidNotification.DisplayType.NOTIFICATION;
        // 如果是退出app的行为，转为消息
        if (appPush.getCustomAfterOpen() != null) {
            if (appPush.getCustomAfterOpen() == 9) {
                displayType = AndroidNotification.DisplayType.MESSAGE;
            }
            // 如果是退出app的行为，转为消息
            if (appPush.getCustomAfterOpen() == 10) {
                displayType = AndroidNotification.DisplayType.MESSAGE;
            }
        }

        // 如果是退出app的行为，转为消息
        if (appPush.getCustomAfterOpen() == 14 && (!appPush.getText().contains("充值蛙豆"))) {
            displayType = AndroidNotification.DisplayType.MESSAGE;
        }
        unicast.setDisplayType(displayType);
        //configName=AfterOpenAction的个数
        if (appPush.getAfterOpen().intValue() >= appPushConfigDao.selectCount
                (new QueryWrapper<HyAppPushConfigEntity>().eq("config_name", "AfterOpenAction"))
                || appPush.getAfterOpen().intValue() < 0) {
            UMENG_LOG.error("点击通知行为不存在,HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
            throw new Exception("点击通知行为不存在");
        }
        //AfterOpenAction = (configName = AfterOpenAction,config_id =appPush.getAfterOpen()）的configValue
        String afterOpenAction = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                .eq("config_name", "AfterOpenAction")
                .eq("config_id", appPush.getAfterOpen())).get(0)
                .getConfigValue();

        if (afterOpenAction.equals("go_app")) {
            unicast.goAppAfterOpen();
        } else {
            // 验证自定义打开后操作
            //customAfterOpenActionSize = (configName=CustomAfterOpenAction的个数)
            int customAfterOpenActionSize = appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction"));
            if (customAfterOpenActionSize <= appPush.getCustomAfterOpen() || appPush.getCustomAfterOpen() < 0) {
                UMENG_LOG.error("不存在的自定义custom，HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
                throw new Exception("不存在的自定义custom");
            }
            //CustomAfterOpenAction =   (configName = CustomAfterOpenAction,config_id =appPush.getCustomAfterOpen()）的configValue
            String CustomAfterOpenAction = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction")
                    .eq("config_id", appPush.getCustomAfterOpen())).get(0)
                    .getConfigValue();
            JSONObject jsonObject = new JSONObject();
            // 自定义打开url的操作
            //如果custom=会议室
            if (CustomAfterOpenAction.equals("go_zoom")) {
				jsonObject.put("data", appPush.getSid().toString());
            } else {
                if(CustomAfterOpenAction.equals("go_meet_end")){
                    jsonObject.put("data", "您的会议还有5分钟结束，请提前准备。");
                }
                jsonObject.put("data", appPush.getNameUrl());
            }
            /*// 可以配合通知到达后，打开App/URL/Custom使用。
            if(CustomAfterOpenAction.equals("go_zoom")){
                unicast.setAfterOpenAction(AndroidNotification.AfterOpenAction.go_custom);
            }*/
            unicast.setAfterOpenAction(AndroidNotification.AfterOpenAction.go_custom);
            jsonObject.put("custom", CustomAfterOpenAction);
            unicast.setCustomField(jsonObject);
        }
        boolean status = new PushClient().send(unicast, appPush);
        if (status) {
//			if (appPush.getType().intValue() == AppPushParam.AppPushType.current) {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.send_success);
//			} else {
//				appPush.setDisplayStatus(AppPushParam.AppPushStatus.timing);
//			}
        } else {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_fail);
        }
        appPushDao.insert(appPush);
        return status;
    }


    /**
     * IOS单发
     *
     * @param appPush
     * @param user_device_token
     * @throws Exception
     */
    public boolean sendIOSUnicast(HyAppPushEntity appPush, String user_device_token) throws Exception {
        UMENG_LOG.info("IOS单发--------------------------------------------");
        appPush.setDisplayChannel(Terminal.DisplayChannel.ios);
        appPush.setStartTime(new Date());
        IOSUnicast broadcast = new IOSUnicast(appkey_ios, appMasterSecret_ios);
        broadcast.setDeviceToken(user_device_token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", appPush.getTitle());
//		map.put("subtitle", appPush.getTicker());
        jsonObject.put("body", appPush.getText());
        broadcast.setAlert(jsonObject);
        broadcast.setBadge(0);
        broadcast.setSound("default");
        if (IPUtils.checkIp() == false) {
            broadcast.setProductionMode();
//			broadcast.setTestMode();
        } else {
            broadcast.setTestMode();
        }
        // 设置时间
        if (appPush.getType().intValue() == AppPushParam.AppPushType.timing) {
            UMENG_LOG.error("单推不能选择定时发送，HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
            throw new Exception("单推不能选择定时发送");
        }

        appPush.setType(AppPushParam.AppPushType.current);
        // 苹果自定义操作
        //AfterOpenAction = (configName = AfterOpenAction,config_id =appPush.getAfterOpen()）的configValue
        String afterOpenAction = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                .eq("config_name", "AfterOpenAction")
                .eq("config_id", appPush.getAfterOpen())).get(0)
                .getConfigValue();
        if (afterOpenAction.equals("go_app")) {
            broadcast.setCustomizedField("custom", afterOpenAction);
        } else if (afterOpenAction.equals("go_custom")) {
            //size = CustomAfterOpenAction的个数
            int size = appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>().eq("config_name", "CustomAfterOpenAction"));
            if (size <= appPush.getCustomAfterOpen() || appPush.getCustomAfterOpen() < 0) {
                UMENG_LOG.error("不存在的自定义custom，HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
                throw new Exception("不存在的自定义custom");
            }

            //cuostomUrl = (configName = CustomAfterOpenAction,config_id =appPush.getCustomAfterOpen()）的configValue
            String customUrl = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction")
                    .eq("config_id", appPush.getCustomAfterOpen())).get(0)
                    .getConfigValue();
            Integer id = null;
            // 自定义打开url的操作
            if (!customUrl.equals("go_link")) {
                if(customUrl.equals("go_zoom")){
                    broadcast.setCustomizedField("data", appPush.getSid().toString());
                }
				/*id = findIdByName(custom, appPush.getNameUrl());
				if(id != null){
					appPush.setSid(id);
					broadcast.setCustomizedField("data", id.toString());
				}
				if(custom.equals(AndroidNotification.CustomAfterOpenAction.go_exit_app.name())){
					broadcast.setCustomizedField("data", "您的账号已被禁用,有问题请联系客服");
				}
				if(custom.equals(AndroidNotification.CustomAfterOpenAction.go_meet_end.name())){
					broadcast.setCustomizedField("data", "您的会议还有10分钟结束，请提前准备。");
				}*/
            } else {
                broadcast.setCustomizedField("data", appPush.getNameUrl());
            }
            if (appPush.getDisplayChannel().intValue() == Terminal.DisplayChannel.ios) {
                // Set customized fields
                broadcast.setCustomizedField("custom", customUrl);
            }
        } else {
            broadcast.setCustomizedField("custom", afterOpenAction);
            broadcast.setCustomizedField("data", appPush.getNameUrl());
        }
        // broadcast.setExpireTime("");
        // 额外传递的参数
        // broadcast.setExtraField("test", "helloworld");
        boolean status = new PushClient().send(broadcast, appPush);
        System.out.println("ios 推送结束");
        if (status) {
//			if (appPush.getType().intValue() == AppPushParam.AppPushType.current) {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.send_success);
//			} else {
//				appPush.setDisplayStatus(AppPushParam.AppPushStatus.timing);
//			}
        } else {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_fail);
        }
        appPushDao.insert(appPush);
        return status;
    }

    @Override
    public boolean sendSingleMessage(HyAppPushEntity appPush) throws Exception {
        UMENG_LOG.info("sendSingleMessage---------------------------------------------------");
//        Integer uid = userService.selectOne(new EntityWrapper<FrogUserEntity>().eq("phone", appPush.getPhone()).setSqlSelect("uid")).getUid().intValue();
        Long uid = 0l;
        if (uid == null) {
            UMENG_LOG.error("用户不存在，HyAppPushEntity对象：" + appPush.toString());
            throw new Exception("用户不存在");
        }
        appPush.setDisplayUid(uid);
        String user_device_token = device_token_cache.get(uid).toString();
        //String user_device_token = "1111111111111111";

        if (StringUtils.isEmpty(user_device_token)) {
            UMENG_LOG.error("用户的设备token不存在，HyAppPushEntity对象：" + appPush.toString());
            throw new Exception("用户的设备token不存在");
        }
        int size = user_device_token.length();
        Boolean status = null;
        if (size == 44) {
            status = sendAndroidUnicast(appPush, user_device_token);
        } else if (size == 64) {
            status = sendIOSUnicast(appPush, user_device_token);
        } else {
            UMENG_LOG.error("用户设备信息不存在，HyAppPushEntity对象：" + appPush.toString());
            throw new Exception("用户设备信息不存在");
        }
        return status;
    }

    @Override
    public void cancleBroadcast(Integer id) throws Exception {
        HyAppPushEntity appPush = appPushDao.selectById(id);
        if (appPush.getStartTime().getTime() <= System.currentTimeMillis()) {
            UMENG_LOG.error("定时时间小于当前时间,无法取消，id:" + id);

            throw new Exception("定时时间小于当前时间,无法取消");
        }
        boolean status = false;
        if (appPush.getDisplayChannel().intValue() == Terminal.DisplayChannel.ios) {
            status = new PushClient().cancle(appPush, appkey_ios, appMasterSecret_ios);
        } else if (appPush.getDisplayChannel().intValue() == Terminal.DisplayChannel.android) {
            status = new PushClient().cancle(appPush, appkey, appMasterSecret);
        } else {
            UMENG_LOG.error("发送渠道不存在，id:" + id);
            throw new Exception("发送渠道不存在");
        }
        if (status) {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.cancel);
            appPushDao.updateById(appPush);
        }
    }

    @Override
    public void checkBroadcastStatus(Integer id) throws Exception {
        HyAppPushEntity appPush = appPushDao.selectById(id);
        if (appPush.getDisplayChannel().intValue() == Terminal.DisplayChannel.ios) {
            int status = new PushClient().checkBroadcastStatus(appPush.getTaskId(), appkey_ios, appMasterSecret_ios);
            appPush.setDisplayStatus(status);
            appPushDao.updateById(appPush);
        } else if (appPush.getDisplayChannel().intValue() == Terminal.DisplayChannel.android) {
            int status = new PushClient().checkBroadcastStatus(appPush.getTaskId(), appkey, appMasterSecret);
            appPush.setDisplayStatus(status);
            appPushDao.updateById(appPush);
        } else {
            UMENG_LOG.error("发送渠道不存在，id:" + id);
            throw new Exception("发送渠道不存在");
        }
    }

    @Override
    public HyAppPushEntity getAppPushById(Integer id) throws Exception {
        return appPushDao.getAppPushById(id);
    }

    @Override
    public Page selectMessageByPage(QueryExt query) {
        Map map = new HashMap();
        map.putAll(query.getCondition());
        /*//查出ios/安卓全推
        List<HyAppPushEntity> result = appPushDao.selectSingleMessageByChannel(query, map);
        //查出单推
        List<HyAppPushEntity> resultSingle = appPushDao.selectMessageByDisplayUid(query, map);
        result.addAll(resultSingle);*/

        List<HyAppPushEntity> result = appPushDao.selectAllMessage(query, map);
        if (result.size() > 0) {

/*            for (HyAppPushEntity appPushEntity : result) {
                if (appPushEntity.getAppMessageType() != null) {
                    HyAppPushConfigEntity appMessage = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                            .eq("config_name", "AppMessageType")
                            .eq("config_id", appPushEntity.getAppMessageType()).setSqlSelect("icon","config_value")).get(0);
                    appPushEntity.setAppMessageIcon(appMessage.getIcon());
                    appPushEntity.setAppMessage(appMessage.getConfigValue());
                }
                if (appPushEntity.getCustomAfterOpen() != null) {
                    HyAppPushConfigEntity module = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                            .eq("config_name", "CustomAfterOpenAction")
                            .eq("config_id", appPushEntity.getCustomAfterOpen()).setSqlSelect("icon","config_value")).get(0);
                    appPushEntity.setModule(module.getConfigValue());
                }
            }*/
        }
        query.setRecords(result);
        return query;
    }

    @Override
    public boolean singleBroadcastByMeetWillEnd(HyAppPushEntity appPush) throws Exception {
        appPush.setDisplayUid(appPush.getUid());
        Object user_device_token = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(appPush.getUid().toString()).toString();
        if (user_device_token == null) {
            throw new Exception("用户的设备token不存在");
        }
        String token = user_device_token.toString();
        int size = token.length();
        Boolean status = null;
        if (size == 44) {
            status = sendAndroidUnicast2(appPush, token);
        }else if(size == 64) {
            status = sendIOSUnicast2(appPush, token);
        }else{
            throw new Exception("用户设备信息不存在");
        }
        return status;
    }

    @Override
    public boolean sendEndMeet(HyZoomMeeting meeting, Long uid) throws Exception {
        // 发送推送
        Object user_device_token = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(uid.toString());
        if (user_device_token == null) {
            UMENG_LOG.error("用户的设备token不存在,AppPush对象：" + uid.toString());
            return false;
        }
        int size = user_device_token.toString().length();
        // 尝试规范推送代码
        if (size == 44) {
            AndroidUnicast unicast = new AndroidUnicast(appkey,appMasterSecret);
            unicast.setDeviceToken(user_device_token.toString());
            unicast.setTicker("会议反馈");
            unicast.setTitle("您的会议已结束，欢迎提意见。");
            unicast.setText("温馨提醒");
            unicast.goAppAfterOpen();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("custom", "go_meetFeedBack");
            jsonObject.put("data", com.alibaba.fastjson.JSONObject.toJSON(meeting));
            unicast.setCustomField(jsonObject);
            unicast.setAfterOpenAction(AndroidNotification.AfterOpenAction.go_custom);
            unicast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
            unicast.setProductionMode();
            OldPushClient client = new OldPushClient();
            client.send(unicast,2);
        } else if (size == 64) {
            IOSUnicast unicast = new IOSUnicast(appkey_ios,appMasterSecret_ios);
            // TODO Set your device token
            unicast.setDeviceToken(user_device_token.toString());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", "会议反馈");
            jsonObject.put("body", "您的会议已结束，欢迎提意见。");
            unicast.setAlert(jsonObject);
            unicast.setBadge( 0);
            unicast.setSound( "default");
            // TODO set 'production_mode' to 'true' if your app is under production mode
            unicast.setTestMode();
            // Set customized fields
            unicast.setCustomizedField("custom","go_meetFeedBack");
            unicast.setCustomizedField("data", com.alibaba.fastjson.JSONObject.toJSON(meeting).toString());
            unicast.setTestMode();
//          unicast.setProductionMode();
            OldPushClient client = new OldPushClient();
            client.send(unicast,1);
        } else {
            UMENG_LOG.error("用户token长度错误：" + uid.toString());
            throw new MyException("用户token长度错误");
        }
        return true;
    }

    @Override
    public boolean applyFriend(Long uid){
        try {
        // 发送推送
        Object user_device_token = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(uid.toString());
        if (user_device_token == null) {
            UMENG_LOG.error("用户的设备token不存在,AppPush对象：" + uid.toString());
            return false;
        }
        int size = user_device_token.toString().length();
        // 尝试规范推送代码
        if (size == 44) {
            AndroidUnicast unicast = new AndroidUnicast(appkey,appMasterSecret);
            unicast.setDeviceToken(user_device_token.toString());
            unicast.setTicker("消息");
            unicast.setTitle("有用户想添加您为好友请注意,请前往app处理");
            unicast.setText("温馨提醒");
            unicast.goAppAfterOpen();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("custom", "go_applyFriend");
            unicast.setCustomField(jsonObject);
            unicast.setAfterOpenAction(AndroidNotification.AfterOpenAction.go_custom);
            unicast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
            unicast.setProductionMode();
            OldPushClient client = new OldPushClient();
            client.send(unicast,2);
        } else if (size == 64) {
            IOSUnicast unicast = new IOSUnicast(appkey_ios,appMasterSecret_ios);
            // TODO Set your device token
            unicast.setDeviceToken(user_device_token.toString());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", "消息");
            jsonObject.put("body", "有用户想添加您为好友,请前往app处理");
            unicast.setAlert(jsonObject);
            unicast.setBadge( 0);
            unicast.setSound( "default");
            // TODO set 'production_mode' to 'true' if your app is under production mode
            unicast.setTestMode();
            // Set customized fields
            unicast.setCustomizedField("custom","go_applyFriend");
            unicast.setTestMode();
            OldPushClient client = new OldPushClient();
            client.send(unicast,1);
        } else {
            UMENG_LOG.error("用户token长度错误：" + uid.toString());
            throw new MyException("用户token长度错误");
        }
        }catch (Exception e){
            throw new MyException(e.getMessage());
        }
        return true;
    }

    @Override
    public boolean estRelation(Long uid, String toAccount){
        try {
            // 发送推送
            Object user_device_token = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(uid.toString());
            if (user_device_token == null) {
                UMENG_LOG.error("用户的设备token不存在,AppPush对象：" + uid.toString());
                return false;
            }
            int size = user_device_token.toString().length();
            // 尝试规范推送代码
            if (size == 44) {
                AndroidUnicast unicast = new AndroidUnicast(appkey,appMasterSecret);
                unicast.setDeviceToken(user_device_token.toString());
                unicast.setTicker("添加成功");
                unicast.setTitle("你们已成功添加为好友,可以开始聊天了。");
                unicast.setText("温馨提醒");
                unicast.goAppAfterOpen();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("custom", "go_estRelation");
                jsonObject.put("data", toAccount);
                unicast.setCustomField(jsonObject);
                unicast.setAfterOpenAction(AndroidNotification.AfterOpenAction.go_custom);
                unicast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
                unicast.setProductionMode();
                OldPushClient client = new OldPushClient();
                client.send(unicast,2);
            } else if (size == 64) {
                IOSUnicast unicast = new IOSUnicast(appkey_ios,appMasterSecret_ios);
                // TODO Set your device token
                unicast.setDeviceToken(user_device_token.toString());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("title", "添加成功");
                jsonObject.put("body", "你们已成功添加为好友,可以开始聊天了。");
                unicast.setAlert(jsonObject);
                unicast.setBadge( 0);
                unicast.setSound( "default");
                // TODO set 'production_mode' to 'true' if your app is under production mode
                unicast.setTestMode();
                // Set customized fields
                unicast.setCustomizedField("custom","go_estRelation");
                unicast.setCustomizedField("data", toAccount);
                unicast.setTestMode();
                OldPushClient client = new OldPushClient();
                client.send(unicast,1);
            } else {
                UMENG_LOG.error("用户token长度错误：" + uid.toString());
                throw new MyException("用户token长度错误");
            }
        }catch (Exception e){
            throw new MyException(e.getMessage());
        }
        return true;
    }


    /**
     * 安卓单推不保存
     *
     * @param appPush
     * @param user_device_token
     * @return
     * @throws Exception
     */
    public boolean sendAndroidUnicast2(HyAppPushEntity appPush, String user_device_token) throws Exception {
        UMENG_LOG.info("安卓单推不保存");
//		appPush = checkStartTime(appPush);
        appPush.setDisplayChannel(Terminal.DisplayChannel.android);
        AndroidUnicast unicast = new AndroidUnicast(appkey, appMasterSecret);
        appPush.setStartTime(new Date());
        // 设置时间
        if (appPush.getType().intValue() == AppPushParam.AppPushType.timing) {
//			unicast.setStartTime(DateUtils.format(appPush.getStartTime()));
            UMENG_LOG.error("单推不能选择定时发送,AppPush对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
            throw new Exception("单推不能选择定时发送");
        }
        appPush.setType(AppPushParam.AppPushType.current);
        unicast.setDeviceToken(user_device_token);
        unicast.setTicker(appPush.getTicker());
        unicast.setTitle(appPush.getTitle());
        unicast.setText(appPush.getText());
        // 设置为生产模式
        unicast.setProductionMode();
        // 目前默认显示给用户信息
        // 如果后续需要改成APP自解析，根据appPush的displayType字段做修改
        AndroidNotification.DisplayType displayType = AndroidNotification.DisplayType.NOTIFICATION;
        // 如果是退出app的行为，转为消息
        if (appPush.getCustomAfterOpen() != null) {
            if (appPush.getCustomAfterOpen() == 9) {
                displayType = AndroidNotification.DisplayType.MESSAGE;
            }
            // 如果是退出app的行为，转为消息
            if (appPush.getCustomAfterOpen() == 10) {
                displayType = AndroidNotification.DisplayType.MESSAGE;
            }
        }
        unicast.setDisplayType(displayType);
        //configName=AfterOpenAction的个数
        if (appPush.getAfterOpen().intValue() >= appPushConfigDao.selectCount
                (new QueryWrapper<HyAppPushConfigEntity>().eq("config_name", "AfterOpenAction"))
                || appPush.getAfterOpen().intValue() < 0) {
            UMENG_LOG.error("点击通知行为不存在,HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
            throw new Exception("点击通知行为不存在");
        }
        //AfterOpenAction = (configName = AfterOpenAction,config_id =appPush.getAfterOpen()）的configValue
        String afterOpenAction = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                .eq("config_name", "AfterOpenAction")
                .eq("config_id", appPush.getAfterOpen())).get(0)
                .getConfigValue();
        UMENG_LOG.info("afterOpenAction:"+afterOpenAction);
        if (afterOpenAction.equals("go_app")) {
            unicast.goAppAfterOpen();
        } else {
            // 验证自定义打开后操作
            //customAfterOpenActionSize = (configName=CustomAfterOpenAction的个数)
            int customAfterOpenActionSize = appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction"));
            UMENG_LOG.info("customAfterOpenActionSize:"+customAfterOpenActionSize);
            if (customAfterOpenActionSize <= appPush.getCustomAfterOpen() || appPush.getCustomAfterOpen() < 0) {
                UMENG_LOG.error("不存在的自定义custom，HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
                throw new Exception("不存在的自定义custom");
            }
            //CustomAfterOpenAction =   (configName = CustomAfterOpenAction,config_id =appPush.getCustomAfterOpen()）的configValue
            String CustomAfterOpenAction = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction")
                    .eq("config_id", appPush.getCustomAfterOpen())).get(0)
                    .getConfigValue();
            UMENG_LOG.info("CustomAfterOpenAction:"+CustomAfterOpenAction);
            JSONObject jsonObject = new JSONObject();
            // 自定义打开url的操作
            //如果custom=会议室
            if (CustomAfterOpenAction.equals("go_zoom")) {
                jsonObject.put("data", appPush.getSid().toString());
            } else {
                if(CustomAfterOpenAction.equals("go_meet_end")){
                    jsonObject.put("data", "您的会议还有5分钟结束，请提前准备。");
                }
                jsonObject.put("data", appPush.getNameUrl());
            }
            // 可以配合通知到达后，打开App/URL/Custom使用。
            unicast.setAfterOpenAction(AndroidNotification.AfterOpenAction.go_custom);
            jsonObject.put("custom", CustomAfterOpenAction);
            unicast.setCustomField(jsonObject);
        }
        boolean status = new PushClient().send(unicast, appPush);
        if (status) {
//			if (appPush.getType().intValue() == AppPushParam.AppPushType.current) {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.send_success);
//			} else {
//				appPush.setDisplayStatus(AppPushParam.AppPushStatus.timing);
//			}
        } else {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_fail);
        }
        return status;
    }

    /**
     * IOS单发不保存
     *
     * @param appPush
     * @param user_device_token
     * @throws Exception
     */
    public boolean sendIOSUnicast2(HyAppPushEntity appPush, String user_device_token) throws Exception {
        UMENG_LOG.info("IOS单发--------------------------------------------");
        appPush.setDisplayChannel(Terminal.DisplayChannel.ios);
        appPush.setStartTime(new Date());
        IOSUnicast broadcast = new IOSUnicast(appkey_ios, appMasterSecret_ios);
        broadcast.setDeviceToken(user_device_token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", appPush.getTitle());
//		map.put("subtitle", appPush.getTicker());
        jsonObject.put("body", appPush.getText());
        broadcast.setAlert(jsonObject);
        broadcast.setBadge(0);
        broadcast.setSound("default");
        if (IPUtils.checkIp() == false) {
            broadcast.setProductionMode();
//			broadcast.setTestMode();
        } else {
            broadcast.setTestMode();
        }
        // 设置时间
        if (appPush.getType().intValue() == AppPushParam.AppPushType.timing) {
            UMENG_LOG.error("单推不能选择定时发送，HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
            throw new Exception("单推不能选择定时发送");
        }

        appPush.setType(AppPushParam.AppPushType.current);
        // 苹果自定义操作
        //AfterOpenAction = (configName = AfterOpenAction,config_id =appPush.getAfterOpen()）的configValue
        String afterOpenAction = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                .eq("config_name", "AfterOpenAction")
                .eq("config_id", appPush.getAfterOpen())).get(0)
                .getConfigValue();
        if (afterOpenAction.equals("go_app")) {
            broadcast.setCustomizedField("custom", afterOpenAction);
        } else if (afterOpenAction.equals("go_custom")) {
            //size = CustomAfterOpenAction的个数
            int size = appPushConfigDao.selectCount(new QueryWrapper<HyAppPushConfigEntity>().eq("config_name", "CustomAfterOpenAction"));
            if (size <= appPush.getCustomAfterOpen() || appPush.getCustomAfterOpen() < 0) {
                UMENG_LOG.error("不存在的自定义custom，HyAppPushEntity对象：" + appPush.toString() + ",用户设备token:" + user_device_token);
                throw new Exception("不存在的自定义custom");
            }

            //cuostomUrl = (configName = CustomAfterOpenAction,config_id =appPush.getCustomAfterOpen()）的configValue
            String customUrl = appPushConfigDao.selectList(new QueryWrapper<HyAppPushConfigEntity>()
                    .eq("config_name", "CustomAfterOpenAction")
                    .eq("config_id", appPush.getCustomAfterOpen())).get(0)
                    .getConfigValue();
            Integer id = null;
            // 自定义打开url的操作
            if (!customUrl.equals("go_link")) {
                if(customUrl.equals("go_zoom")){
                    broadcast.setCustomizedField("data", appPush.getSid().toString());
                }
				/*id = findIdByName(custom, appPush.getNameUrl());
				if(id != null){
					appPush.setSid(id);
					broadcast.setCustomizedField("data", id.toString());
				}
				if(custom.equals(AndroidNotification.CustomAfterOpenAction.go_exit_app.name())){
					broadcast.setCustomizedField("data", "您的账号已被禁用,有问题请联系客服");
				}
				if(custom.equals(AndroidNotification.CustomAfterOpenAction.go_meet_end.name())){
					broadcast.setCustomizedField("data", "您的会议还有10分钟结束，请提前准备。");
				}*/
            } else {
                broadcast.setCustomizedField("data", appPush.getNameUrl());
            }
            if (appPush.getDisplayChannel().intValue() == Terminal.DisplayChannel.ios) {
                // Set customized fields
                broadcast.setCustomizedField("custom", customUrl);
            }
        } else {
            broadcast.setCustomizedField("custom", afterOpenAction);
            broadcast.setCustomizedField("data", appPush.getNameUrl());
        }
        // broadcast.setExpireTime("");
        // 额外传递的参数
        // broadcast.setExtraField("test", "helloworld");
        boolean status = new PushClient().send(broadcast, appPush);
        System.out.println("ios 推送结束");
        if (status) {
//			if (appPush.getType().intValue() == AppPushParam.AppPushType.current) {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.send_success);
//			} else {
//				appPush.setDisplayStatus(AppPushParam.AppPushStatus.timing);
//			}
        } else {
            appPush.setDisplayStatus(AppPushParam.AppPushStatus.up_fail);
        }
        return status;
    }


    @Override
    public void coinPush(Long uid,Integer coin,Integer code) throws Exception {
        // 如果是安卓,可以走原来的方法,IOS的话重写推送并静默
        String user_device_token = (String)redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(uid.toString());
        TaskEntity taskEntity = taskService.getOne(new QueryWrapper<TaskEntity>().eq("code", code));
        if (StringUtils.isEmpty(user_device_token)) {
            throw new ServiceException("用户的设备token不存在");
        }
        int size = user_device_token.length();
        if (size == 44) {
            /*HyAppPushEntity appPush = new HyAppPushEntity();
            // 点击"通知"的后续行为，默认为打开app
            appPush.setAfterOpen(1);
            appPush.setCustomAfterOpen(14);
            appPush.setTitle("您有积分到账");
            appPush.setText(taskEntity.getName()+"+" + coin.toString() + "个积分");
            appPush.setTicker("请注意");
            appPush.setType(AppPushParam.AppPushType.current);
            appPush.setUid(uid);
            // 推送范围，0全部，1个体
            appPush.setDisplayRange(1);
            // 推送渠道：ios/andriod
            appPush.setDisplayChannel(2);
            sendAndroidUnicast(appPush, user_device_token);*/
            UmAndriodNotification um=(UmAndriodNotification) UmPushUtil.getUotificationBySys(UmConfig.Sys.Android.name(),UmConfig.CasetType.unicast.name(),null);
            um.setTitle("您有积分到账");
            um.setText(taskEntity.getName()+"+" + coin.toString() + "个积分");
            um.setTicker("请注意");
            um.setDisplayType(UmConfig.DisplayType.message.name());
            um.goCustomAfterOpen("14");
            UmPushUtil.sendUmRequest(um);
        } else if (size == 64) {
            IOSUnicast unicast = new IOSUnicast(appkey_ios, appMasterSecret_ios);
            unicast.setDeviceToken(user_device_token);
            if (IPUtils.checkIp() == false) {
                unicast.setProductionMode();
            } else {
                unicast.setTestMode();
            }
            unicast.setContentAvailable(1);
            // 业务起点 ios静默推送 第一个参数自定义让ios那边获取，第二个参数是需要推送的业务逻辑
            unicast.setCustomizedField("SHARE_INFO", taskEntity.getName()+"+" + coin.toString() + "个积分");
            PushClient client = new PushClient();
            client.sendIos(unicast);
        } else {
            throw new ServiceException("用户设备信息不存在");
        }
    }

    @Override
    public boolean singleBroadcastByBan(HyAppPushEntity appPush) throws Exception {
        appPush.setDisplayUid(appPush.getUid());
        Object user_device_token = redisUtils.getMap(FrogConstant.RedisKey.DEVICE_TOKEN).get(appPush.getUid().toString());
        if (user_device_token == null) {
            throw new Exception("用户的设备token不存在");
        }
        String token = user_device_token.toString();
        int size = token.length();
        Boolean status = null;
        if (size == 46) {
            token = token.substring(1,45);
            status = sendAndroidUnicast(appPush, token);
        } else if (size == 66) {
            token = token.substring(1,65);
            status = sendIOSUnicast(appPush, token);
        } else {
            throw new ServiceException("用户设备信息不存在");
        }
        return status;
    }
}
